package com.springbootsecuritydemo.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.sun.xml.internal.ws.api.ha.HaInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 封装UserEntity
 * 重写UserDetails方法
 *
 * @author Daft_V
 * @date 2022/4/7 14:58
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private UserEntity userEntity;

    //存储权限信息
    private List<String> permissions;

    @JSONField(serialize = false)
    private List<GrantedAuthority> grantedAuthorityList;

    /**
     * 自定义构造器,用户添加用户实体类和权限信息
     *
     * @param userEntity  用户实体类
     * @param permissions 权限信息
     */
    public LoginUser(UserEntity userEntity, List<String> permissions) {
        this.userEntity = userEntity;
        this.permissions = permissions;
    }

    /**
     * 获取权限信息
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        grantedAuthorityList = new ArrayList<>();
        for (String permission : permissions
        ) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            grantedAuthorityList.add(authority);
        }
        return grantedAuthorityList;
    }

    /**
     * 获取密码
     *
     * @return
     */
    @Override
    public String getPassword() {
        return userEntity.getPassword();
    }

    /**
     * 获取用户名
     *
     * @return
     */
    @Override
    public String getUsername() {
        return userEntity.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
